#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>


int main()
{
    // socket(协议族，类型，0)
    int client_sockfd = socket(AF_INET, SOCK_STREAM, 0); 
    if (client_sockfd == -1) {
        fprintf(stderr, "error on socket errno=%d : %m\n", errno);
        return 1;
    }

    struct sockaddr_in server_sockaddr;
    bzero(&server_sockaddr, sizeof(server_sockaddr));
    //sin_family指代协议族，在socket编程中只能是AF_INET
    server_sockaddr.sin_family = AF_INET;
    //sin_port存储端口号（使用网络字节顺序）
    server_sockaddr.sin_port   = htons(8887);
    server_sockaddr.sin_addr.s_addr = inet_addr("10.172.198.86");
    //server_sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);

    if (connect(client_sockfd, (struct sockaddr*)&server_sockaddr, sizeof(server_sockaddr)) == -1) {
        fprintf(stderr, "error on connect %d:%m\n", errno);
        return 1;
    }

    const int BUF_SIZE = 1024;
    char sendbuf[BUF_SIZE];
    char recvbuf[BUF_SIZE];
    memset(sendbuf, 0, sizeof(sendbuf));
    memset(recvbuf, 0, sizeof(recvbuf));
    while (fgets(sendbuf, sizeof(sendbuf), stdin) != NULL) {
        send(client_sockfd, sendbuf, sizeof(sendbuf), 0);
        if (strcmp(sendbuf, "bye\n") == 0) {
            break;
        }
        recv(client_sockfd, recvbuf, sizeof(recvbuf), 0);
        fprintf(stdout, "%s", recvbuf);
        memset(sendbuf, 0, sizeof(sendbuf));
        memset(recvbuf, 0, sizeof(recvbuf));
    }
    close(client_sockfd);

    return 0;
}
